#include "ws2812_app.h"
#include <math.h>


// 灯效控制器实例
LedEffectController led_controller;

// 初始化灯效控制器
void LED_Effect_Init(LedEffectController *ctrl, uint16_t led_count) 
{
    // 初始化灯环
    WS2812_RingInit(&ctrl->ring);
    
    // 默认参数
    ctrl->params.type = EFFECT_MARQUEE;
    ctrl->params.color = (RGB_Color){255, 0, 0}; // 红色
    ctrl->params.speed = 100; // 100ms
    ctrl->params.brightness = 80; // 80%亮度
    
    // 状态初始化
    ctrl->last_update = HAL_GetTick();
    ctrl->position = 0;
    
    // 设置初始亮度
    WS2812_SetBrightness(&ctrl->ring, ctrl->params.brightness);
}

// 设置灯效参数
void LED_Effect_SetParams(LedEffectController *ctrl, LedEffectParams params) 
{
    ctrl->params = params;
    WS2812_SetBrightness(&ctrl->ring, params.brightness);
    ctrl->position = 0; // 重置动画位置
}

// 跑马灯效果
static void effect_marquee(LedEffectController *ctrl) 
{
    // 清除所有LED
    WS2812_ClearAll(&ctrl->ring);
    
    // 设置当前位置的LED
    WS2812_SetLEDColor(&ctrl->ring, ctrl->position, ctrl->params.color);
    
    // 移动位置
    ctrl->position = (ctrl->position + 1) % LED_NUM;
}

// 纯色常亮
static void effect_solid_color(LedEffectController *ctrl) 
{
    WS2812_SetAllColor(&ctrl->ring, ctrl->params.color);
}

// 呼吸灯效果
static void effect_breathing(LedEffectController *ctrl) 
{
    // 计算呼吸波形 (0-1范围)
    static uint8_t breath_dir = 0;
    static float breath_val = 0.0f;
    const float step = 0.02f;
    
    if (breath_dir == 0) {
        breath_val += step;
        if (breath_val >= 1.0f) {
            breath_val = 1.0f;
            breath_dir = 1;
        }
    } else {
        breath_val -= step;
        if (breath_val <= 0.0f) {
            breath_val = 0.0f;
            breath_dir = 0;
        }
    }
    
    // 应用呼吸亮度
    RGB_Color color = ctrl->params.color;
    color.r = (uint8_t)(color.r * breath_val);
    color.g = (uint8_t)(color.g * breath_val);
    color.b = (uint8_t)(color.b * breath_val);
    
    WS2812_SetAllColor(&ctrl->ring, color);
}

// 彩虹渐变效果
static void effect_rainbow(LedEffectController *ctrl) 
{
    for (int i = 0; i < LED_NUM; i++) {
        // 计算HSV中的Hue (0-360)
        float hue = ((i + ctrl->position) % LED_NUM) * 360.0f / LED_NUM;
        
        // HSV转RGB
        float s = 1.0f, v = 1.0f;
        float c = v * s;
        float x = c * (1 - fabs(fmod(hue / 60.0f, 2) - 1));
        float m = v - c;
        
        float r, g, b;
        if (hue < 60) {
            r = c; g = x; b = 0;
        } else if (hue < 120) {
            r = x; g = c; b = 0;
        } else if (hue < 180) {
            r = 0; g = c; b = x;
        } else if (hue < 240) {
            r = 0; g = x; b = c;
        } else if (hue < 300) {
            r = x; g = 0; b = c;
        } else {
            r = c; g = 0; b = x;
        }
        
        RGB_Color color = {
            .r = (uint8_t)((r + m) * 255),
            .g = (uint8_t)((g + m) * 255),
            .b = (uint8_t)((b + m) * 255)
        };
        
        WS2812_SetLEDColor(&ctrl->ring, i, color);
    }
    
    // 移动彩虹位置
    ctrl->position = (ctrl->position + 1) % LED_NUM;
}

// 弹跳球效果
static void effect_bouncing_ball(LedEffectController *ctrl) {
    static float position = 0;
    static float velocity = 0.5;
    static float gravity = 0.05;
    
    // 清除所有LED
    WS2812_ClearAll(&ctrl->ring);
    
    // 物理模拟
    position += velocity;
    velocity -= gravity;
    
    // 地面碰撞
    if (position < 0) {
        position = -position;
        velocity = -velocity * 0.8; // 能量损失
    }
    
    // 天花板碰撞
    if (position > LED_NUM - 1) {
        position = 2 * (LED_NUM - 1) - position;
        velocity = -velocity * 0.8;
    }
    
    // 绘制球体
    int ball_pos = (int)position;
    float fraction = position - ball_pos;
    
    // 主球体
    WS2812_SetLEDColor(&ctrl->ring, ball_pos, ctrl->params.color);
    
    // 拖尾效果
    for (int i = 1; i <= 3; i++) {
        int trail_pos = ball_pos - i;
        if (trail_pos >= 0) {
            float intensity = 1.0 - 0.2 * i;
            RGB_Color trail_color = {
                .r = (uint8_t)(ctrl->params.color.r * intensity),
                .g = (uint8_t)(ctrl->params.color.g * intensity),
                .b = (uint8_t)(ctrl->params.color.b * intensity)
            };
            WS2812_SetLEDColor(&ctrl->ring, trail_pos, trail_color);
        }
    }
}

// 彗星拖尾效果
static void effect_comet(LedEffectController *ctrl) {
    // 清除所有LED
    WS2812_ClearAll(&ctrl->ring);
    
    // 计算拖尾长度
    int tail_length = ctrl->params.size ? ctrl->params.size : 5;
    
    // 绘制彗星和拖尾
    for (int i = 0; i < tail_length; i++) {
        int pos = (ctrl->position - i + LED_NUM) % LED_NUM;
        
        // 计算拖尾亮度衰减
        float brightness = 1.0f - (float)i / tail_length;
        RGB_Color color = {
            .r = (uint8_t)(ctrl->params.color.r * brightness),
            .g = (uint8_t)(ctrl->params.color.g * brightness),
            .b = (uint8_t)(ctrl->params.color.b * brightness)
        };
        
        WS2812_SetLEDColor(&ctrl->ring, pos, color);
    }
    
    // 移动位置
    ctrl->position = (ctrl->position + 1) % LED_NUM;
}

// 火焰效果
static void effect_fire(LedEffectController *ctrl) {
    static uint8_t heat[LED_NUM];
    
    // 火焰强度 (0-255)
    uint8_t base_intensity = ctrl->params.intensity ? ctrl->params.intensity : 200;
    
    // 1. 生成热源
    for (int i = 0; i < 3; i++) {
        int pos = rand() % (LED_NUM / 4);
        heat[pos] = base_intensity + rand() % 55;
    }
    
    // 2. 热传导（向上扩散）
    for (int i = LED_NUM - 1; i >= 2; i--) {
        heat[i] = (heat[i-1] + heat[i-2] + heat[i-2]) / 3;
    }
    
    // 3. 冷却（随机冷却）
    for (int i = 0; i < LED_NUM; i++) {
        uint8_t cooling = rand() % 4;
        heat[i] = (heat[i] > cooling) ? heat[i] - cooling : 0;
    }
    
    // 4. 转换为颜色
    for (int i = 0; i < LED_NUM; i++) {
        // 热值到颜色的映射
        uint8_t t = heat[i];
        RGB_Color color;
        
        // 冷色（蓝色）到热色（红色）的渐变
        if (t < 85) {
            color.r = t * 3;
            color.g = 0;
            color.b = 0;
        } else if (t < 170) {
            color.r = 255;
            color.g = (t - 85) * 3;
            color.b = 0;
        } else {
            color.r = 255;
            color.g = 255;
            color.b = (t - 170) * 3;
        }
        
        WS2812_SetLEDColor(&ctrl->ring, i, color);
    }
}

// 颜色擦除效果
static void effect_color_wipe(LedEffectController *ctrl) {
    // 设置所有LED为背景色
    WS2812_SetAllColor(&ctrl->ring, ctrl->params.color2);
    
    // 绘制前景色擦除效果
    for (int i = 0; i < ctrl->position; i++) {
        WS2812_SetLEDColor(&ctrl->ring, i, ctrl->params.color);
    }
    
    // 更新位置
    ctrl->position = (ctrl->position + 1) % (LED_NUM + 1);
    
    // 重置位置
    if (ctrl->position == LED_NUM) {
        // 交换颜色，实现双向擦除
        RGB_Color temp = ctrl->params.color;
        ctrl->params.color = ctrl->params.color2;
        ctrl->params.color2 = temp;
    }
}

// 频闪效果
static void effect_strobe(LedEffectController *ctrl) {
    static uint8_t state = 0;
    
    if (state) {
        WS2812_SetAllColor(&ctrl->ring, ctrl->params.color);
    } else {
        WS2812_ClearAll(&ctrl->ring);
    }
    
    state = !state;
}

// 环形彩虹
static void effect_circular_rainbow(LedEffectController *ctrl) 
{
    for (int i = 0; i < LED_NUM; i++) {
        // 计算HSV中的Hue (0-360)
        float hue = (i * 360.0f / LED_NUM + ctrl->position) / 2;
        
        // HSV转RGB
        float s = 1.0f, v = 1.0f;
        float c = v * s;
        float x = c * (1 - fabs(fmod(hue / 60.0f, 2) - 1));
        float m = v - c;
        
        float r, g, b;
        if (hue < 60) {
            r = c; g = x; b = 0;
        } else if (hue < 120) {
            r = x; g = c; b = 0;
        } else if (hue < 180) {
            r = 0; g = c; b = x;
        } else if (hue < 240) {
            r = 0; g = x; b = c;
        } else if (hue < 300) {
            r = x; g = 0; b = c;
        } else {
            r = c; g = 0; b = x;
        }
        
        RGB_Color color = {
            .r = (uint8_t)((r + m) * 255),
            .g = (uint8_t)((g + m) * 255),
            .b = (uint8_t)((b + m) * 255)
        };
        
        WS2812_SetLEDColor(&ctrl->ring, i, color);
    }
    
    // 移动位置
    ctrl->position = (ctrl->position + 1) % 360;
}

// 脉冲波浪
static void effect_pulse_wave(LedEffectController *ctrl) {
    static float pulse_pos = 0.0f;
    
    // 计算波浪参数
    float wave_speed = 0.05f;
    float wave_width = LED_NUM / 4.0f;
    
    // 更新波浪位置
    pulse_pos += wave_speed;
    if (pulse_pos > LED_NUM) pulse_pos = 0;
    
    for (int i = 0; i < LED_NUM; i++) {
        // 计算距离波浪中心的距离
        float dist = fabs(i - pulse_pos);
        if (dist > LED_NUM / 2) dist = LED_NUM - dist;
        
        // 计算亮度 (高斯分布)
        float intensity = exp(-(dist * dist) / (2 * wave_width * wave_width));
        
        RGB_Color color = {
            .r = (uint8_t)(ctrl->params.color.r * intensity),
            .g = (uint8_t)(ctrl->params.color.g * intensity),
            .b = (uint8_t)(ctrl->params.color.b * intensity)
        };
        
        WS2812_SetLEDColor(&ctrl->ring, i, color);
    }
}


// 星光闪烁效果
static void effect_twinkle(LedEffectController *ctrl) {
    static uint8_t sparkle_intensity[LED_NUM] = {0};
    
    // 随机生成新的闪烁点
    for (int i = 0; i < ctrl->params.intensity; i++) {
        int pos = rand() % LED_NUM;
        if (sparkle_intensity[pos] == 0) {
            sparkle_intensity[pos] = 200 + rand() % 55;
        }
    }
    
    // 更新所有LED
    for (int i = 0; i < LED_NUM; i++) {
        if (sparkle_intensity[i] > 0) {
            // 闪烁点 - 使用主色
            float factor = sparkle_intensity[i] / 255.0;
            RGB_Color color = {
                .r = (uint8_t)(ctrl->params.color.r * factor),
                .g = (uint8_t)(ctrl->params.color.g * factor),
                .b = (uint8_t)(ctrl->params.color.b * factor)
            };
            WS2812_SetLEDColor(&ctrl->ring, i, color);
            
            // 衰减
            sparkle_intensity[i] -= 5 + rand() % 10;
            if (sparkle_intensity[i] < 0) sparkle_intensity[i] = 0;
        } else {
            // 背景 - 使用次色
            WS2812_SetLEDColor(&ctrl->ring, i, ctrl->params.color2);
        }
    }
}

// 更新灯效
void LED_Effect_Update(LedEffectController *ctrl) 
{
    uint32_t current_time = HAL_GetTick();
    
    // 检查是否达到更新间隔
    if (current_time - ctrl->last_update < ctrl->params.speed) 
	{
        return;
    }
    
    ctrl->last_update = current_time;
    
	// 根据效果类型调用对应函数
	 switch (ctrl->params.type) 
	 {
		 case EFFECT_SOLID_COLOR:
			 effect_solid_color(ctrl);
			 break;
			 
		 case EFFECT_MARQUEE:
			 effect_marquee(ctrl);
			 break;
			 
		 case EFFECT_BREATHING:
			 effect_breathing(ctrl);
			 break;
			 
		 case EFFECT_RAINBOW:
			 effect_rainbow(ctrl);
			 break;
			 
		 case EFFECT_COMET:
			 effect_comet(ctrl);
			 break;
			 
		 case EFFECT_FIRE:
			 effect_fire(ctrl);
			 break;
			 
		 case EFFECT_COLOR_WIPE:
			 effect_color_wipe(ctrl);
			 break;
			 
		 case EFFECT_STROBE:
			 effect_strobe(ctrl);
			 break;
			 
		 case EFFECT_CIRCULAR_RAINBOW:
			 effect_circular_rainbow(ctrl);
			 break;
			 
		 case EFFECT_PULSE_WAVE:
			 effect_pulse_wave(ctrl);
			 break;
			 
		 case EFFECT_BOUNCING_BALL:
			 effect_bouncing_ball(ctrl);
			 break;
			 
		 case EFFECT_TWINKLE:
			 effect_twinkle(ctrl);
			 break;
	 }
	 
    // 更新物理灯带
    WS2812_UpdateRing(&ctrl->ring);
}


// 设置所有LED为绿色常亮
LedEffectParams solid_green = {
    .type = EFFECT_SOLID_COLOR,
    .color = {0, 255, 0},   // 绿色
    .speed = 0,             // 不需要更新速度
    .brightness = 70        // 70%亮度
};
//LED_Effect_SetParams(&led_controller, solid_green);

// 设置所有LED为白色高亮度
LedEffectParams solid_white = {
    .type = EFFECT_SOLID_COLOR,
    .color = {255, 255, 255}, // 白色
    .brightness = 100         // 100%亮度
};
//LED_Effect_SetParams(&led_controller, solid_white);

// 设置所有LED为紫色中等亮度
LedEffectParams solid_purple = {
    .type = EFFECT_SOLID_COLOR,
    .color = {128, 0, 255}, // 紫色
    .brightness = 80         // 80%亮度
};
//LED_Effect_SetParams(&led_controller, solid_purple);

// 红色光点快速移动
LedEffectParams red_marquee = {
    .type = EFFECT_MARQUEE,
    .color = {255, 0, 0},   // 红色
    .speed = 50,            // 50ms移动一次（快速）
    .brightness = 90        // 90%亮度
};
//LED_Effect_SetParams(&led_controller, red_marquee);

// 蓝色光点中等速度移动
LedEffectParams blue_marquee = {
    .type = EFFECT_MARQUEE,
    .color = {0, 0, 255},   // 蓝色
    .speed = 150,           // 150ms移动一次（中等速度）
    .brightness = 100       // 100%亮度
};
//LED_Effect_SetParams(&led_controller, blue_marquee);

// 蓝色呼吸灯，快速呼吸
LedEffectParams blue_breathing = {
    .type = EFFECT_BREATHING,
    .color = {0, 0, 255},   // 蓝色
    .speed = 20,            // 20ms更新一次（快速呼吸）
    .brightness = 100       // 最大亮度100%
};
//LED_Effect_SetParams(&led_controller, blue_breathing);

// 粉色呼吸灯，中等速度
LedEffectParams pink_breathing = {
    .type = EFFECT_BREATHING,
    .color = {255, 105, 180}, // 粉色
    .speed = 50,              // 50ms更新一次
    .brightness = 90          // 最大亮度90%
};
//LED_Effect_SetParams(&led_controller, pink_breathing);

// 白色呼吸灯，慢速呼吸
LedEffectParams white_breathing = {
    .type = EFFECT_BREATHING,
    .color = {255, 255, 255}, // 白色
    .speed = 100,             // 100ms更新一次（慢速呼吸）
    .brightness = 80          // 最大亮度80%
};
//LED_Effect_SetParams(&led_controller, white_breathing);

// 标准彩虹效果，快速移动
LedEffectParams fast_rainbow = {
    .type = EFFECT_RAINBOW,
    .speed = 30,            // 30ms更新一次（快速移动）
    .brightness = 100       // 100%亮度
};
//LED_Effect_SetParams(&led_controller, fast_rainbow);

// 彩虹效果，中等速度
LedEffectParams medium_rainbow = {
    .type = EFFECT_RAINBOW,
    .speed = 100,           // 100ms更新一次
    .brightness = 90        // 90%亮度
};
//LED_Effect_SetParams(&led_controller, medium_rainbow);

// 彩虹效果，慢速移动
LedEffectParams slow_rainbow = {
    .type = EFFECT_RAINBOW,
    .speed = 200,           // 200ms更新一次（慢速移动）
    .brightness = 80        // 80%亮度
};
//LED_Effect_SetParams(&led_controller, slow_rainbow);


// 黄色光点慢速移动
LedEffectParams yellow_marquee = {
    .type = EFFECT_MARQUEE,
    .color = {255, 255, 0}, // 黄色
    .speed = 300,           // 300ms移动一次（慢速）
    .brightness = 80        // 80%亮度
};
//LED_Effect_SetParams(&led_controller, yellow_marquee);

// 彗星效果（蓝色拖尾）
LedEffectParams comet_params = {
    .type = EFFECT_COMET,
    .color = {0, 0, 255},     // 蓝色
    .size = 8,                 // 拖尾长度
    .speed = 50,               // 移动速度
    .brightness = 80
};
//LED_Effect_SetParams(&led_controller, comet_params);

// 火焰效果
LedEffectParams fire_params = {
    .type = EFFECT_FIRE,
    .intensity = 200,          // 火焰强度
    .speed = 50,               // 更新速度
    .brightness = 90
};
//LED_Effect_SetParams(&led_controller, fire_params);

// 颜色擦除效果（红蓝交替）
LedEffectParams wipe_params = {
    .type = EFFECT_COLOR_WIPE,
    .color = {255, 0, 0},      // 红色
    .color2 = {0, 0, 255},     // 蓝色
    .speed = 30,               // 擦除速度
    .brightness = 100
};
//LED_Effect_SetParams(&led_controller, wipe_params);

// 弹跳球效果（绿色球）
LedEffectParams ball_params = {
    .type = EFFECT_BOUNCING_BALL,
    .color = {0, 255, 0},      // 绿色
    .speed = 20,               // 物理更新速度
    .brightness = 100
};
//LED_Effect_SetParams(&led_controller, ball_params);

// 星光闪烁效果（黄色星星，深蓝背景）
LedEffectParams twinkle_params = {
    .type = EFFECT_TWINKLE,
    .color = {255, 255, 0},    // 黄色
    .color2 = {0, 0, 30},      // 深蓝背景
    .intensity = 3,            // 每帧新星星数量
    .speed = 100,              // 更新速度
    .brightness = 100
};
//LED_Effect_SetParams(&led_controller, twinkle_params);

void ws2812_app_init(void)
{
	// 初始化灯效控制器
	LED_Effect_Init(&led_controller, LED_NUM);

	LED_Effect_SetParams(&led_controller, comet_params);
}





